﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using CSM_SQL;
using CSM_SQL.BLL;
using Newtonsoft.Json;

namespace CommunitySuperMarketManager.Controllers
{
    public class EmpController : Controller
    {
        private EmpBLL _EmpBll;
        
        private EmpBLL eb
        {
            get
            {
                if (_EmpBll == null)
                    _EmpBll = new EmpBLL();
                return _EmpBll;
            }
        }
        // GET: Emp
        public ActionResult Emp()
        {
            var e = (Emp)HttpContext.Session["CurrUser"];
            if (e != null)
            {
                ViewBag.CurrUser = e;
                if (e.Auth > 0)
                    return View();
                else
                    return RedirectToAction("PersonalOrders", "PersonalMsg");
            }
            return RedirectToAction("Login", "Login");
        }

        public ActionResult Assess()
        {
            var e = (Emp)HttpContext.Session["CurrUser"];
            if (e != null)
            {
                ViewBag.CurrUser = e;
                if (e.Auth > 0)
                    return View();
                else
                    return RedirectToAction("PersonalOrders", "PersonalMsg");
            }
            return RedirectToAction("Login", "Login");

        }

        public void AllAss()
        {
            var pageNamber = Convert.ToInt32(Request.Params["page"]);
            var pageSize = Convert.ToInt32(Request.Params["rows"]);

            var list = eb.GetAssess().OrderByDescending(a => a.startTime).OrderByDescending(a => a.grade);
            Hashtable ht = new Hashtable
            {
               { "total", list.Count() },
               { "rows", list.Take((pageSize * pageNamber)).Skip(pageSize * (pageNamber - 1)).ToList() }
            };
            HttpContext.Response.Write(JsonConvert.SerializeObject(ht));
            HttpContext.Response.End();
        }

        public void Search()
        {
            var pageNamber = Convert.ToInt32(Request.Params["pageNamber"]);
            var pageSize = Convert.ToInt32(Request.Params["pageSize"]);
            var type1 = Convert.ToInt32(Request.Params["type1"]);
            var type2 = Convert.ToInt32(Request.Params["type2"]);
            var text = Request.Params["selecttext"];
            List<AssessMsg> list = eb.GetAssess();
            if (type1 == 0)
                list = list.OrderByDescending(a => a.startTime).ToList();
            else
                list = list.OrderBy(a => a.startTime).ToList();

            if(type2 == 0)
                list = list.OrderByDescending(a => a.grade).ToList();
            else
                list = list.OrderBy(a => a.grade).ToList();
            if (!string.IsNullOrEmpty(text))
                list = list.Where(a => a.goodsName.Contains(text) || a.customer.Contains(text) || a.postName.Contains(text) || a.assess.Contains(text) || a.startTime.ToString().Contains(text) || a.endTime.ToString().Contains(text)).ToList();
            Hashtable ht = new Hashtable
            {
               { "total", list.Count() },
               { "rows", list.Take((pageSize * pageNamber)).Skip(pageSize * (pageNamber - 1)).ToList() }
            };
            HttpContext.Response.Write(JsonConvert.SerializeObject(ht));
            HttpContext.Response.End();
        }

        public void All()
        {
            var pageNamber = Convert.ToInt32(Request.Params["page"]);
            var pageSize = Convert.ToInt32(Request.Params["rows"]);

            List<Emp> list = eb.All();
            Hashtable ht = new Hashtable
            {
               { "total", list.Count() },
               { "rows", list.Take((pageSize * pageNamber)).Skip(pageSize * (pageNamber - 1)).ToList<Emp>() }
            };
            HttpContext.Response.Write(JsonConvert.SerializeObject(ht));
            HttpContext.Response.End();
        }

        public void Add()
        {
            
            Emp emp = new Emp
            {
                Auth = Convert.ToInt32(Request.Form["Auth"]),
                Name = Request.Form["Name"],
                Password = MD5BLL.EncryptString(Request.Form["Password"]),
                Phone = Request.Form["Phone"],
                State = 0
            };
            if (eb.Add(emp))
                HttpContext.Response.Write(0);
            else
                HttpContext.Response.Write(1);
            HttpContext.Response.End();

        }

        public void GetOrder(int ID)
        {
            HttpContext.Response.Write(JsonConvert.SerializeObject(eb.GetOrder(ID).Where(ord=>ord.state < 3)));
            HttpContext.Response.End();
        }

        public void ChangeState()
        {
            var id = Convert.ToInt32(Request.Params["ID"]);
            var state = Convert.ToInt32(Request.Params["state"]);
            if (eb.ChangeState(id, state))
                HttpContext.Response.Write(0);
            else
                HttpContext.Response.Write(1);
            HttpContext.Response.End();
        }

        public void Select()
        {
            var pageNamber = Convert.ToInt32(Request.Params["pageNumber"]);
            var pageSize = Convert.ToInt32(Request.Params["pageSize"]);
            var state = Convert.ToInt16(Request.Params["state"]);
            var auth = Convert.ToInt16(Request.Params["auth"]);
            var selecttext = Request.Params["selecttext"];

            var list = eb.All();
            if (state != -1)
                list = (from l in list where l.State == state select l).ToList();
            if(auth != -1)
                list = (from l in list where l.Auth == auth select l).ToList();
            if(!string.IsNullOrEmpty(selecttext))
                list = (from l in list where l.Name.Contains(selecttext) || l.Phone.Contains(selecttext) select l).ToList();

            Hashtable ht = new Hashtable
            {
               { "total", list.Count() },
               { "rows", list.Take((pageSize * pageNamber)).Skip(pageSize * (pageNamber - 1)).ToList<Emp>() }
            };
            HttpContext.Response.Write(JsonConvert.SerializeObject(ht));
            HttpContext.Response.End();
        }

        public ActionResult Exit()
        {
            HttpContext.Session["CurrUser"] = null;
            return RedirectToAction("Login", "Login");
        }

        public void ValidName()
        {
            var newName = Request.Params["newName"];
            if ((from e in eb.All() where e.Name == newName select e.Name).Count() == 0)
                HttpContext.Response.Write(0);
            else
                HttpContext.Response.Write(1);
            HttpContext.Response.End();
        }

        public void ValidPwd()
        {
            var pwd = MD5BLL.EncryptString(Request.Params["pwd"]);
            var e = (Emp)HttpContext.Session["CurrUser"];
            if (e.Password == pwd)
                HttpContext.Response.Write(0);
            else
                HttpContext.Response.Write(1);
            HttpContext.Response.End();
        }

        public void ChangePwd()
        {
            var id = Request.Params["id"];
            var pwd = Request.Params["newPwd"];
            Emp e = new CSM_SQL.Emp { E_ID = Convert.ToInt32(id), Password = pwd };
            if (eb.ChangePwd(e))
                HttpContext.Response.Write(0);
            else
                HttpContext.Response.Write(1);
            HttpContext.Response.End();
        }

        public ActionResult Charts()
        {
            var e = (Emp)HttpContext.Session["CurrUser"];
            if (e != null)
            {
               
                ViewBag.CurrUser = e;
                if (e.Auth > 0)
                    return View();
                else
                    return RedirectToAction("PersonalOrders", "PersonalMsg");
            }
            return RedirectToAction("Login", "Login");
        }

        public void GetIncomeTable()
        {
            var startTime = Convert.ToDateTime(Request.Params["startTime"]);
            var endTime =  Convert.ToDateTime(Request.Params["endTime"]);
            var now = DateTime.Now;
            if(startTime <= new DateTime(1000, 1, 1))
            {
                startTime = new DateTime(now.Year, now.Month, 1);
            }
            if(endTime <= new DateTime(1000,1,1) )
            {
                endTime = new DateTime(now.Year, now.Month,now.Day);
            }

            var a = eb.getIncomeTable(startTime, endTime).OrderBy(o=>o.Date).Select(s=>new { Date=s.Date.Value.ToShortDateString(),s.Income1});
            HttpContext.Response.Write(JsonConvert.SerializeObject(a));
            HttpContext.Response.End();
        }
    }

    
}